const webpack = require("webpack");
const path = require("path");
const config = require("../../webpack.config");
var sockjs = require("sockjs");
const compiler = webpack(config);
var http = require("http");
const express = require("express");
const opn = require("opn");
const router = require("./router"); //  引入路由
var bodyParser = require("body-parser");
const MemoryFs = require('memory-fs');


const mfs = new MemoryFs();
compiler.outputFileSystem = mfs;
class Server {
    constructor(compiler) {
        this.lastHash = null;
        this.app = express();
        this.sockets = [];
        this.initSocket(9999);
        this.initWebpack(compiler);
        this.initRouter();
        this.openFlag = false;
    }
    initWebpack(compiler) {
        const { compile, invalid, done } = compiler.hooks;
        compiler.watch({ watch: true }, (err, stats) => {
            console.log("【webpack】开始监听文件修改...");
            if (!this.openFlag) {
                this.openFlag = opn("http://localhost:8080");
            }
        });
        done.tap("webpack-dev-server", (stats) => {
            console.log("【hash】current hash:", stats.hash);
            if (stats.hash != this.lastHash) {
                this.lastHash = stats.hash;
                console.log("【webpack】 hash change");
                this.sockets.forEach((socket) => {
                    socket.emit("hash", stats.hash);
                    socket.emit("ok");
                });
            }
        });
        // compiler.run((e) => console.log("【webpack】编译失败：", e));
    }
    initSocket(port) {
        var sock = sockjs.createServer();
        const that = this;
        sock.on("connection", function (conn) {
            conn.emit = function (type, value) {
                this.write(
                    JSON.stringify({
                        type,
                        value,
                    })
                );
            };
            console.log("【Socket】连接成功");
            conn.emit("hash", that.lastHash);
            that.sockets.push(conn);
            conn.on("data", function (message) {
                console.log("【Socket】接收到消息：", message);
            });
            conn.on("close", function () {
                console.log("【Socket】连接已关闭");
            });
        });
        var server = http.createServer();
        server.listen(port);
        sock.installHandlers(server, { prefix: "/node-socket" });
        console.log("【websocket】socket在端口%d启动", port);
    }
    initRouter() {
        this.app.use(bodyParser.json());
        this.app.use(`/phone`, router);
    }
    listen(port) {
        // this.app.use(express.static(path.resolve(__dirname, "../../dist")));
        this.app.get('*', function (req, res) {
            let filename = req.params[0].slice(1) || 'index.html'
            const source = path.join(config.output.path, filename)
            res.end(mfs.readFileSync(source, 'utf-8'))
        })
        this.app.listen(port);
        console.log("【express】系统在%s端口启动", port);
    }
}

let server = new Server(compiler);
server.listen(8080);
